package com.jhw.ymcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.jhw.ymcc.dto.PayExtParamsDto;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.service.ICourseUserLearnService;
import com.jhw.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "tx-course-pay-consumer-group",
        topic = "tx-pay-notify-topic",
        selectorExpression = "tx-pay-notify-tag",
        messageModel = MessageModel.BROADCASTING // 我们订单结果出来消费消息需要是广播
)
public class CoursePayAsyncNotifyTxConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private ICourseUserLearnService courseUserLearnService;

    /**
     * 消费者有一个签收模式：
     *  什么都不返回：签收成功
     *  报错了：签收失败，重新发送
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.业务校验
        byte[] body = messageExt.getBody();
        String paramStr = new String(body, StandardCharsets.UTF_8);
        PayExtParamsDto payExtParamsDto = JSON.parseObject(paramStr, PayExtParamsDto.class);
        AssertUtil.isNotNull(payExtParamsDto, GlobalErrorCode.ERROR);


        courseUserLearnService.saveCourseUserLearn(payExtParamsDto);
    }
}